/*
 * @Author: 徐建辰
 * @Date: 2022-04-15 15:08:41
 * @LastEditTime: 2022-06-21 09:00:02
 * @LastEditors: xjc
 * @Description: 本地缓存处理(兼容local和session)
 */
import {isString, isArray, isObject} from './type'
import {TOKEN, USER_INFO, MENU} from './constant'

// unified set get
export const setItem = (key, value, type = 'localStorage') => {
  if (!key) return
  if (!value) throw new Error('value is required')
  if (isArray(value) || isObject(value)) {
    value = JSON.stringify(value)
  }

  return window[type].setItem(key, value)
}
export const getItem = (key, type = 'localStorage') => {
  if (!key) return
  let data = window[type].getItem(key)
  try {
    const jsonData = JSON.parse(data)

    if (isArray(jsonData) || isObject(jsonData)) return jsonData
    else return data
  } catch (error) {
    return data || null
  }
}

// unified remove
export const removeItem = (key, type = 'localStorage') => {
  if (!key) return
  window[type].removeItem(key)
}
export const removeAll = (type = 'localStorage') => {
  if (!isString(type)) throw new Error('type must be a string')
  window[type].clear()
}

// token
export const setToken = value => setItem(TOKEN, value)
export const getToken = () => getItem(TOKEN)
export const removeToken = () => removeItem(TOKEN)

// userInfo
export const setUser = value => setItem(USER_INFO, value)
export const getUser = () => getItem(USER_INFO)
export const removeUser = () => removeItem(USER_INFO)

// menu
export const setMenu = value => setItem(MENU, value)
export const getMenu = () => getItem(MENU)
export const removeMenu = () => removeItem(MENU)